package cn.jsu.oj.dispatchServer.satellite.factory;

import cn.jsu.oj.dispatchServer.satellite.annotation.StarterAnn;
import cn.jsu.oj.dispatchServer.satellite.netty.starter.Starter;
import cn.jsu.oj.dispatchServer.satellite.util.AnnScanUtil;
import cn.jsu.oj.dispatchServer.satellite.util.SpringUtil;
import cn.jsu.oj.dispatchServer.satellite.util.StringUtil;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 启动器工厂
 *
 * @author shan
 * @date 2022/07/07
 */
public class StarterFactory implements Factory {

    private Map<Short, Starter> starterMap;

    @Override
    public void build() {
        this.starterMap = new ConcurrentHashMap<>(10);
        List<Class<?>> classList = AnnScanUtil.scanPackage("cn", StarterAnn.class);
        for (Class<?> clazz : classList) {
            Short starterNo = clazz.getAnnotation(StarterAnn.class).starter();
            String[] strings = clazz.getName().split("\\.");
            String beanName = StringUtil.initialFormat(strings[strings.length - 1], false);
            if (SpringUtil.getBean(clazz) == null) {
                SpringUtil.registerBean(beanName, clazz, false);
            }
            this.starterMap.put(starterNo, (Starter) SpringUtil.getBean(beanName));
        }
    }

    @Override
    public Object getProduct(Short goodsNo) {
        if (goodsNo == 0) {
            return this.starterMap;
        }
        return this.starterMap.get(goodsNo);
    }
}
